from pymongo import MongoClient
import pandas as pd

# 1. 连接MongoDB
client = MongoClient('mongodb://localhost:27017/')  # 替换为你的MongoDB连接字符串
db = client['test']
logs_collection = db['logs']

# 2. 从MongoDB读取数据并转换为DataFrame
cursor = logs_collection.find({"action": "read"})  # 只查询阅读行为
df = pd.DataFrame(list(cursor))

if not df.empty:
    # 3. 分析数据：统计每本书的阅读次数
    book_read_counts = df['b_id'].value_counts().reset_index()
    book_read_counts.columns = ['b_id', 'read_count']
    top_50_books = book_read_counts.head(50).to_dict('records')

    # 4. 将结果存储到MongoDB的新集合中
    result_collection = db['bestseller_books']
    result_collection.delete_many({})  # 清空现有数据（可选）
    result_collection.insert_many(top_50_books)  # 插入新数据

    print("成功分析并存储了阅读量最高的前50本图书！")
else:
    print("没有找到阅读记录数据。")

# 关闭连接
client.close()